<template>
  <div class="code">
    <div class="v_code">
      <input
        ref="vcode"
        id="vcode"
        type="tel"
        maxlength="6"
        :value="value"
        v-bind="$attrs"
        v-on="$listener"
        @focus="focused = true"
        @blur="focused = false"
        :disabled="telDisabled"
        @input="$emit('input', $event.target.value)"
      />

      <label
        for="vcode"
        class="line"
        v-for="(item, index) in codeLength"
        :key="index"
        :class="{ animated: focused && cursorIndex === index }"
        v-text="codeArr[index]"
      >
      </label>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      default: "123",
      type: String || Number,
    },
  },
  data() {
    return {
      code: "",
      codeLength: 6,
      telDisabled: false,
      focused: false,
    };
  },
  computed: {
    codeArr() {
      return this.value.split("");
    },
    cursorIndex() {
      return this.value.length;
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.vcode.focus();
    });
  },
  watch: {
    value(newVal) {
      console.log(newVal);
      this.value = newVal.replace(/[^\d]/g, "");
      if (newVal.length >= 6) {
        // this.telDisabled = true
        this.$refs.vcode.blur();
      }
    },
  },
};
</script>

<style>
.code {
  display: flex;
  align-items: center;
  justify-content: center;
}
.v_code {
  width: 6.9rem;
  height: 1.08rem;
  border: 0.02rem solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.v_code input {
  width: 100%;
  height: 100%;
  position: absolute;
  opacity: 0;
}

.v_code .line {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 100%;
  font-size: 0.46rem;
}

.v_code .line:nth-child(-n + 6)::after {
  display: block;
  position: absolute;
  content: "";
  right: 0;
  top: 0.1rem;
  width: 0.02rem;
  height: 80%;
  background-color: #ccc;
  /* transform: scaleY(0.5);
  transform-origin: 0 100%; */
}

.v_code .line.animated::before {
  display: block;
  position: absolute;
  left: 55%;
  top: 0.25rem;
  width: 0.02rem;
  height: 50%;
  content: "";
  background-color: #333333;
  animation-name: coruscate;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-fill-mode: both;
}

@keyframes coruscate {
  0% {
    opacity: 0;
  }

  25% {
    opacity: 0;
  }

  50% {
    opacity: 1;
  }

  75% {
    opacity: 1;
  }

  to {
    opacity: 0;
  }
}
</style>